import { defineStore } from 'pinia';
import { store } from '@/store';
import { IParam } from '@/core';

interface ViewActionState {
	appViews: any[];
	viewSplit: IParam;
}

const useViewActionStore = defineStore({
	id: 'viewAction',
	state: (): ViewActionState => ({
		appViews: [],
		viewSplit: {},
	}),
	getters: {
		getStateByPath() {
			return (path: string): boolean => {
				if (path) {
					const appView = this.appViews.find((appView: any) =>
						Object.is(appView.path, path)
					);
					if (appView) {
						return appView.viewDataSate;
					}
				}
				return false;
			};
		},
		getStateByTag() {
			return (tag: string): boolean => {
				if (tag) {
					const appView = this.appViews.find((appView: any) =>
						Object.is(appView.tag, tag)
					);
					if (appView) {
						return appView.viewDataSate;
					}
				}
				return false;
			};
		},
		getViewSplit() {
			return (tag: string): number | undefined => {
				if (this.viewSplit.hasOwnProperty(tag)) {
					return this.viewSplit[tag];
				}
				return undefined;
			};
		},
	},
	actions: {
		setViewSplit(tag: string, split: number) {
			this.viewSplit[tag] = split;
		},
		addAppViews(path: string, tag: string) {
			const index = this.appViews.findIndex((appView: any) =>
				Object.is(appView.tag, tag)
			);
			if (index) {
				this.appViews.splice(index, 1, { path, tag });
			} else {
				this.appViews.push({ path, tag });
			}
		},
		setViewDataState(tag: string, viewDataSate: boolean) {
			if (tag) {
				const appView = this.appViews.find((appView: any) =>
					Object.is(appView.tag, tag)
				);
				if (appView) {
					Object.assign(appView, { viewDataSate });
				}
			}
		},
		removeAppViewsByTag(tag: string) {
			if (tag) {
				const index = this.appViews.findIndex((appView: any) =>
					Object.is(appView.tag, tag)
				);
				if (index > -1) {
					this.appViews.splice(index, 1);
				}
			}
		},
		removeAppViewsByPath(path: string) {
			if (path) {
				const index = this.appViews.findIndex((appView: any) =>
					Object.is(appView.path, path)
				);
				if (index > -1) {
					this.appViews.splice(index, 1);
				}
			}
		},
	},
});

export function useViewActionStoreWithOut() {
	return useViewActionStore(store);
}
